package net.contrend.util;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RightsFilter implements Filter {

    /**
     * 系统的登录页面
     */
    private String loginPage;
    
    /**
     * 不需要过滤的URI
     */
    private Set<String> ignoreURI = new HashSet<String>(0);

    @Override
    public void destroy() {
        this.loginPage = null;
        this.ignoreURI.clear();
        this.ignoreURI = null;
        System.gc();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest hsr = (HttpServletRequest) request;
        HttpServletResponse hsp = (HttpServletResponse) response;
        HttpSession session = hsr.getSession();
        
        String ctx = hsr.getContextPath();
        if ("/".equals(ctx)) {
            ctx = "";
        }
        String uri = hsr.getRequestURI();
        if (!this.ignoreURI.contains(uri.replaceFirst(ctx, ""))) {
            Object user = session.getAttribute(Constants.USER_LOGIN_ID);
            if (null == user) {
                hsp.sendRedirect(ctx + this.loginPage);
                return;
            }
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.loginPage = config.getInitParameter("loginPage");
        String ignoreURI = config.getInitParameter("ignoreURI");
        if (StringUtils.isNotBlank(ignoreURI)) {
            String[] uris = ignoreURI.replaceAll("\\s", "").split(",");
            for (String uri : uris) {
                if (StringUtils.isNotBlank(uri)) {
                    this.ignoreURI.add(uri);
                }
            }
        }
    }

}
